package com.jie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jie.entity.User;
import com.jie.service.UserService;
import com.jie.utility.JwtUtils;
import com.jie.utility.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jie
 * @since 2024-03-01
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 生成6位随机数
     */
    @GetMapping("/randomCode")
    public R<String> randomCode() {
        int c=(int) ((Math.random() * 9 + 1) * 100000);
        String code= String.valueOf(c);
        return R.success(code);
    }
    @PostMapping("/sign")
    public R<String> sign(@RequestBody User user){
        if(user!=null){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotEmpty(user.getPhone()),User::getPhone,user.getPhone());
            List<User> list = userService.list(queryWrapper);
            if(list.size()<0){
                user.setUserName(user.getPhone());
                boolean save = userService.save(user);
                if(save){
                    return R.success("注册成功");
                }
            }else {
                return R.error("手机号已经注册");
            }

        }
        return R.error("注册失败");
    }
    @PostMapping("/login")
    public R<String> getUser(HttpServletRequest request,@RequestBody User user){
        LambdaQueryWrapper<User> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(user.getPhone()),User::getPhone,user.getPhone());
        queryWrapper.eq(StringUtils.isNotEmpty(user.getUserName()),User::getUserName,user.getUserName());
        User one = userService.getOne(queryWrapper);
        if(one!=null){
            if(user.getUserName()!=null){
                if(!one.getPassword().equals(user.getPassword())){
                    return R.error("密码错误");
                }
            }
            Map<String,Object> claims=new HashMap<>();
            request.getSession().setAttribute("userId",one.getUserId());
            claims.put("userId",one.getUserId());
            claims.put("userName",one.getUserName());
            claims.put("phone",one.getPhone());
            String jwt = JwtUtils.generateJwt(claims);
            String key="userId:"+one.getUserId();
            String o = (String) redisTemplate.opsForValue().get(key);
            if(com.alibaba.cloud.commons.lang.StringUtils.isNotEmpty(o)){
                redisTemplate.delete(key);
            }
            redisTemplate.opsForValue().set(key,jwt,30l , TimeUnit.MINUTES);
            return R.success(jwt);
        }
        return R.error("没有该用户");
    }
    @GetMapping ("/logout")
    public R<String> logout(HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        R r = JwtUtils.parseJwt(jwt);
        Map map = r.getMap();
        Integer userId= (Integer) map.get("userId");
        String key="userId:"+userId;
        Boolean delete = redisTemplate.delete(key);
        if(delete){
            request.getSession().removeAttribute("userId");
            return R.success("退出成功");
        }
        return R.success("退出成功");

    }
    @GetMapping("/test")
    public R<User> test(HttpServletRequest request) {
        String jwt = request.getHeader("Authorization");
        if (jwt == null) {
            return R.error("没有登录");
        }
        R r = JwtUtils.parseJwt(jwt);
        Map map = r.getMap();
        if (map.get("userId").toString() == null) {
            return R.error("NOTLOGIN");
        }
        User user = userService.getById(map.get("userId").toString());
        return R.success(user,map);
    }
    @PutMapping ("/editUser")
    public  R<String> editUser(@RequestBody User user){
        if(user.getUserName()!=null||user.getPhone()!=null){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotEmpty(user.getUserName()),User::getUserName,user.getUserName());
            queryWrapper.eq(StringUtils.isNotEmpty(user.getPhone()),User::getPhone,user.getPhone());
            List<User> list = userService.list(queryWrapper);
            if(list.size()>0){
                return R.error("用户名已经存在");
            }
        }
        boolean b = userService.updateById(user);
        if(b){
            return R.success("修改成功！");
        }
        return R.error("修改失败");
    }
    @DeleteMapping("/delUser")
    public R<String> delUser(int id){
        boolean b = userService.removeById(id);
        if(b){
            return R.success("注销用户成功！");
        }
        return R.error("注销用户失败！");
    }

}

